<?php


namespace App\Bizs\Mp1;


use App\Models\MessageModel;
use App\Models\UserModel;
use App\Supports\DateSupport;
use Base\BaseBiz;

class MessageBiz extends BaseBiz
{
    /**
     * 分页获取消息
     * @param $params
     * @param $uid
     * @return array
     */
    public function getMyMessages($params, $uid)
    {
        list($count, $data) = (new MessageModel())->getMessgaeByUid($uid, [
            'is_read' => 'ASC',
            'create_time' => 'DESC'
        ], $params['limit'] ?? 20, $params['page'] ?? 1);

        if (empty($data)) {
            return ['count' => $count, 'data' => $data];
        }

        $users = (new UserModel())->getUserDirByUid(
            array_merge(
                array_column($data, 'from'),
                array_column($data, 'to')
            ), [
                'id', 'nickname', 'icon'
            ]
        );

        foreach ($data as &$v) {
            $v['from_user'] = $users[$v['from']] ?? [];
        }

        // 所有都设为已读
        (new MessageModel())->setAllMyMessageRead($uid);
        return ['count' => $count, 'data' => $data];
    }

    public function sendMessage($to, $type, $cmd, $uid = 10001, $content = '')
    {
        return (new MessageModel())->insertMessage([
            'from' => $uid,
            'to' => $to,
            'type' => $type,
            'is_read' => 0,
            'content' => $content,
            'cmd' => $cmd,
            'create_time' => DateSupport::nowDate(),
            'is_del' => 0
        ]);
    }
}
